// pages/cashService/third/doCount/doCount.js
const { request } = require('../../../../utils/request');
Page({

  /**
   * 页面的初始数据
   */
  data: {
    canEdit:false, //三方操作能否修改箱包信息
    activeNames:0,
    activeNames2:0,
    showAmConfirm:false,
    bagInfo: {
      accountDate: '',
      accountId: '',
      accountName: '',
      accountNo: '',
      backAmount: '',
      bagsStatus: '',
      checkAmount: '',
      checkDate: '',
      checkResult: '',
      checkStatus: '',
      checkUserCode: '',
      checkUserName: '',
      companyId: 0,
      companyName: '',
      counterfeitAmount: '',
      counterparty: '',
      entryAmount: '',
      fundName: '',
      gapAmount: '',
      id: 0,
      inputAmount: '',
      inputStatus: '',
      orderId: 0,
      orderNo: '',
      payDate: '',
      payer: '',
      payerPhoneNum: '',
      qrcodeNo: '',
      staffId: 0,
      stationId: 0,
      stationName: '',
      stationNo: '',
      voucherDate: '',
      bagsNum: 0,
      totalAmount: '',
      realCashAmount: '',
      adjustAmount: ''
    },
    checkAmount: '',
    counterfeitAmount: '',
    entryAmount: '',
    backAmount: '',
    returnAmount: '',
    checkResult: 'INPUT',
    tempRes: '',
    ifInput: true,
    coinCount: [],
    check100centAmount: '',
    check50centAmount: '',
    check10centAmount: ''
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    wx.setNavigationBarTitle({
      title: '清点箱包',
    })
    let item = JSON.parse(options.bagInfo)
    this.setData({
      canEdit: wx.getStorageSync('userInfo').canEdit,
      bagInfo:item,
      checkAmount:this.functiontoDecimal2(item.inputAmount),
      counterfeitAmount:this.functiontoDecimal2(item.counterfeitAmount),
      entryAmount:this.functiontoDecimal2(item.inputAmount),
      returnAmount:this.functiontoDecimal2(item.returnAmount),
      backAmount:this.functiontoDecimal2(item.backAmount),
      check100centAmount:this.functiontoDecimal2(item.check100centAmount),
      check50centAmount:this.functiontoDecimal2(item.check50centAmount),
      check10centAmount:this.functiontoDecimal2(item.check10centAmount),
      checkResult:item.checkResult,
      ifInput:item.checkResult == 'BACK'? false : true
    })
  },
  /**
   * 列表展开
   */
  collapseChange(event) {
    this.setData({
      activeNames: event.detail,
    });
  },
   /**
   * 列表展开2
   */
  collapseChange_2(event) {
    this.setData({
      activeNames2: event.detail,
    });
  },
  // 选择是否入账
  handleIfInput (e) {
    
    if(e.target.dataset.result == 1){
      this.setData({
        ifInput:true,
        //选择入账或退回直接赋值，不让操作员输入金额
        checkAmount:this.functiontoDecimal2(this.data.bagInfo.inputAmount),
        entryAmount:this.functiontoDecimal2(this.data.bagInfo.inputAmount),
        backAmount: 0
      })
    }else{
      this.setData({
        ifInput:false,
        checkAmount:this.functiontoDecimal2(this.data.bagInfo.inputAmount),
        entryAmount:0,
        backAmount:this.functiontoDecimal2(this.data.bagInfo.inputAmount)
      })
    }
    
    if (e.target.dataset.result == 1) {
      this.data.checkResult = 'INPUT'
    } else {
      this.data.checkResult = 'BACK'
      this.setData({
        backAmount:this.data.checkAmount,
        entryAmount:''
      })
    }
  },
  // 选择按交款金额入账/清点金额入账
  handleResult (str) {
    this.data.tempRes = str
    if (str == 'ORIGIN') {
      this.data.entryAmount = this.data.bagInfo.inputAmount
    }
    if (str == 'CHECK') {
      this.data.entryAmount = this.data.checkAmount
    }
  },
  // 提交处理结果
  submit (e) {
    var str = e.currentTarget.dataset.mode;
    // console.log(e.currentTarget.dataset.mode);
    if (str === 'TODO') {
      this.data.checkResult = 'TODO'
    } else {
      if (this.data.ifInput) {
        this.data.backAmount = 0
        this.data.checkResult = 'INPUT'

        if ( Number(this.data.checkAmount) === 0 || this.data.checkAmount === '' ){
          wx.showToast({
            title: '请输入清点真币',
            icon: 'error'
          })
          return
        }
        
        if (Number(this.data.entryAmount) === 0  || this.data.entryAmount === '') {
          wx.showToast({
            title: '请输入入账金额',
            icon: 'error'
          })
          return
        }

        //清点真币或入账金额与客户交款金额不一致时提示
        if( Number(this.data.entryAmount) !== Number(this.data.bagInfo.inputAmount) || Number(this.data.checkAmount) !== Number(this.data.bagInfo.inputAmount)){
          console.log(this.data.entryAmount,this.data.inputAmount,this.data.checkAmount)
          this.setData({
            showAmConfirm:true
          })
          return
        }

        Number(this.data.entryAmount) !== Number(this.data.checkAmount)
      } else {
        this.data.entryAmount = 0
        this.data.returnAmount = 0
        this.data.checkResult = 'BACK'
        if ( Number(this.data.checkAmount) === 0 || this.data.checkAmount === '' ){
          wx.showToast({
            title: '请输入清点真币',
            icon: 'error'
          })
          return
        }
        if (Number(this.data.backAmount) === 0 || this.data.backAmount === '') {
          wx.showToast({
            title: '请输入退回金额',
            icon: 'error'
          })
          return
        }
      }
    }

    // if (this.checkResult === '') {
    //   Toast('请选择处理结果')
    //   return
    // }
    if (Number(this.data.check100centAmount) + Number(this.data.check50centAmount) + Number(this.data.check10centAmount) > Number(this.data.checkAmount)) {
      wx.showToast({
        title: '硬币总金额大于清点金额，请确认',
        icon: 'none'
      })
      return
    }
    this.doSub();
  },
  doSub(){
    let query = {
      id: this.data.bagInfo.id,
      qrcodeNo: this.data.bagInfo.qrcodeNo,
      checkAmount: Number(this.data.checkAmount),
      counterfeitAmount: Number(this.data.counterfeitAmount),
      checkResult: this.data.checkResult,
      entryAmount: Number(this.data.entryAmount),
      backAmount: Number(this.data.backAmount),
      returnAmount: this.data.returnAmount ? Number(this.data.returnAmount) : 0,
      check100centAmount: Number(this.data.check100centAmount),
      check50centAmount: Number(this.data.check50centAmount),
      check10centAmount: Number(this.data.check10centAmount)
    }

    if (this.data.counterfeitAmount === null || this.data.counterfeitAmount === '') {
      query.counterfeitAmount = 0
    }
    console.log(query)

    request('/smsk/outsource/submit', 'POST', query).then(res => {
      console.log(res)
      if (res.data.code === 0) {
        wx.showToast({
          title: '保存成功',
          icon: 'success'
        })
        wx.redirectTo({
          url: '/pages/cashService/third/list/list'
        })
      }else{
        console.log(res.data.message)
        wx.showToast({
          title: res.data.message,
          icon:'none'
        })
      }
    })
  },
  functiontoDecimal2 (x) {
    var f = parseFloat(x)
    if (isNaN(f)) {
      return ''
    }
    f = Math.round(x * 100) / 100
    var s = f.toString()
    var rs = s.indexOf('.')
    if (rs < 0) {
      rs = s.length
      s += '.'
    }
    while (s.length <= rs + 2) {
      s += '0'
    }
    return s
  },
  /**
   * 金额输入事件
   */
  amountInput(){
    var gapAmount = this.gapAmount();
    var adjustAmount = this.adjustAmount();
    this.setData({
      gapAmount:gapAmount,
      adjustAmount:adjustAmount
    })
  },
  /**
   * 金额输入框失焦事件
   */
  amountBlur(){
    this.setData({
      checkAmount:this.functiontoDecimal2(this.data.checkAmount),
      counterfeitAmount:this.functiontoDecimal2(this.data.counterfeitAmount),
      entryAmount:this.functiontoDecimal2(this.data.entryAmount),
      returnAmount:this.functiontoDecimal2(this.data.returnAmount),
      backAmount:this.functiontoDecimal2(this.data.backAmount),
      check100centAmount:this.functiontoDecimal2(this.data.check100centAmount),
      check50centAmount:this.functiontoDecimal2(this.data.check50centAmount),
      check10centAmount:this.functiontoDecimal2(this.data.check10centAmount),
    })
  },
  /**
   * 库存调整金额
   */
  adjustAmount: function () {
    // 库存调整=清点真币 - 入账金额 （- 应退客户金额）
    var tempAmount = '—'
    if (this.data.checkAmount && this.data.entryAmount) {
      // 真币-入账
      tempAmount = this.data.checkAmount - this.data.entryAmount
      // -应退
      if (this.data.returnAmount) {
        let tempRe = parseFloat(this.data.returnAmount)
        tempAmount = tempAmount - tempRe
      }
      tempAmount = this.functiontoDecimal2(tempAmount)
    } else {
      tempAmount = '—'
    }
    return tempAmount
  },
  /**
   * 长短款计算
   */
  gapAmount: function () {
    // // 长短款=入账+假币-交款金额
    // 长短款 = 真币 - 库存调整 - 交款金额 =（ 入账 + 退客户 - 交款？ ）
    var tempAmount = '—'
    if (this.data.entryAmount) {
      let tempRe = this.data.returnAmount ? this.data.returnAmount : 0
      tempAmount = parseFloat(this.data.entryAmount) + parseFloat(tempRe) - parseFloat(this.data.bagInfo.inputAmount)
      tempAmount = this.functiontoDecimal2(tempAmount)
    } else {
      tempAmount = '—'
    }
    return tempAmount
  }
})